//
//  PPBLEDeviceTableViewController.m
//  PetParadise
//
//  Created by Frank on 9/5/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#define kServiceUUID @"FFF0"
#define kDeviceName @"iChaser"
#define kSavedDeviceListKey @"pairedDeviceList"

#import "PPBLEDeviceTableViewController.h"
@import CoreBluetooth;
@import QuartzCore;
#import "UIAlertView+Blocks.h"
#import "CBUUID+UUIDString.h"

@interface PPBLEDeviceTableViewController () <CBCentralManagerDelegate, CBPeripheralDelegate>

@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) NSMutableArray *deviceArray;
@property (nonatomic, strong) NSMutableArray *pairedDeviceArray;

@end

@implementation PPBLEDeviceTableViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.deviceArray = [NSMutableArray array];
    self.pairedDeviceArray = [[NSUserDefaults standardUserDefaults] objectForKey:kSavedDeviceListKey];
    
    if (!self.pairedDeviceArray) {
        self.pairedDeviceArray = [NSMutableArray array];
    }
    
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    [self.centralManager scanForPeripheralsWithServices:nil options:nil];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"已配对设备";
    } else {
        return @"已发现设备";
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.pairedDeviceArray.count;
    } else {
        return self.deviceArray.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"deviceListCell" forIndexPath:indexPath];
    
    if (indexPath.section == 0) {
        cell.textLabel.text = kDeviceName;
        cell.detailTextLabel.text = [self.pairedDeviceArray objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = kDeviceName;
        CBPeripheral *peripheral = [self.deviceArray objectAtIndex:indexPath.row];
        
        
        cell.detailTextLabel.text = peripheral.identifier.UUIDString;
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CBPeripheral *peripheral = [self.deviceArray objectAtIndex:indexPath.row];
//    int index = [self.deviceArray indexOfObject:peripheral];
    NSString *UUIDString = peripheral.identifier.UUIDString;
    BOOL alreadyExist = NO;
    for (NSString *string in self.pairedDeviceArray) {
        if ([string isEqual:UUIDString]) {
            alreadyExist = YES;
        }
    }
    if (!alreadyExist) {
        [self.pairedDeviceArray addObject:UUIDString];
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:self.pairedDeviceArray forKey:kSavedDeviceListKey];
    [self.tableView reloadData];
//    [self.centralManager connectPeripheral:peripheral options:nil];
}



// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return YES;
    }
    return NO;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [self.pairedDeviceArray removeObjectAtIndex:indexPath.row];
        [[NSUserDefaults standardUserDefaults] setObject:self.pairedDeviceArray forKey:kSavedDeviceListKey];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Blue Tooth Delegate

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSString *deviceName = advertisementData[CBAdvertisementDataLocalNameKey];
    NSArray *serviceUUIDs = advertisementData[CBAdvertisementDataServiceUUIDsKey];
    if ([deviceName isEqual:kDeviceName]) {
//        for (CBUUID *uuid in serviceUUIDs) {
//            CFStringRef fooBar = CFUUIDCreateString(NULL, (__bridge CFUUIDRef)uuid);
//            if ([(__bridge NSString *)fooBar isEqual:kServiceUUID]) {
                if (![self.deviceArray containsObject:peripheral]) {
                    [self.deviceArray addObject:peripheral];
                    [self.tableView reloadData];
                }
//            }
//        }
    }
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            NSLog(@"CentralManagerState PoweredOn");
            [self.centralManager scanForPeripheralsWithServices:nil options:nil];
            break;
        case CBCentralManagerStateUnknown :
            NSLog(@"CentralManagerState Unknown");
            break;
        case CBCentralManagerStateResetting :
            NSLog(@"CentralManagerState Resetting");
            break;
        case CBCentralManagerStateUnsupported :
            NSLog(@"CentralManagerState Unsupported");
            [UIAlertView showWithTitle:@"此设备硬件不支持" message:@"宠物防走失智能在支持蓝牙4.0的设备上使用" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];

            break;
        case CBCentralManagerStatePoweredOff :
            [UIAlertView showWithTitle:@"蓝牙未打开" message:@"请开启设备蓝牙，以使用宠物防走失功能" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
            break;
        default:
            NSLog(@"Central Manager did change state");
            break;
            
    }
    
}


- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    
}

@end
